<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var Light = function(){
            this.state = 'off';    // 给电灯设置初始状态off
            this.button = null;    // 电灯开关按钮
        };
        Light.prototype.init = function(){
            var button = document.createElement( 'button' ),
              self = this;

            button.innerHTML = '开关';
            this.button = document.body.appendChild( button );
            this.button.onclick = function(){
              self.buttonWasPressed();
            }
        };
        Light.prototype.buttonWasPressed = function(){
            if ( this.state === 'off' ){
              console.log( '开灯' );
              this.state = 'on';
            }else if ( this.state === 'on' ){
              console.log( '关灯' );
              this.state = 'off';
            }
        };

        var light = new Light();
        light.init();
    </script>
</body>
</html>